#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
为 Neo4j 概念数据库添加 vue 相关的测试数据
"""

import asyncio
import sys
import os
from pathlib import Path
from datetime import datetime

# 添加项目根目录到路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
sys.path.insert(0, str(project_root / "src"))

# 设置环境变量
os.environ['PYTHONPATH'] = str(project_root / "src")

async def create_vue_concept_data():
    """为 Neo4j 添加 vue 相关概念数据"""
    print("=== 为 Neo4j 添加 vue 相关概念数据 ===")
    
    try:
        # 1. 导入必要模块
        print("\n1. 导入模块...")
        
        from src.core.context_orchestrator import ContextOrchestrator
        from src.config import load_config
        
        # 2. 加载配置并初始化
        print("\n2. 初始化系统...")
        config = load_config()
        context_orchestrator = ContextOrchestrator(config)
        await context_orchestrator.initialize()
        
        neo4j_client = context_orchestrator.db_manager.neo4j_client
        print("✓ Neo4j 连接成功")
        
        # 3. 检查当前概念数据
        print("\n3. 检查当前概念数据...")
        
        # 查看是否已有 vue 相关概念
        query = """
        MATCH (c:Concept)
        WHERE toLower(c.concept_id) CONTAINS 'vue' OR toLower(c.name) CONTAINS 'vue'
        RETURN c.concept_id, c.name
        LIMIT 10
        """
        existing_vue_concepts = await neo4j_client.execute_query(query)
        print(f"现有 vue 相关概念数量: {len(existing_vue_concepts)}")
        
        if existing_vue_concepts:
            print("现有 vue 概念:")
            for record in existing_vue_concepts:
                print(f"  - ID: {record['c.concept_id']}, 名称: {record['c.name']}")
        
        # 4. 创建 vue 相关概念
        print("\n4. 创建 vue 相关概念...")
        
        vue_concepts = [
            {
                "concept_id": "vue",
                "name": "Vue.js",
                "description": "渐进式JavaScript框架，用于构建用户界面",
                "category": "前端框架",
                "tags": ["JavaScript", "前端", "框架", "响应式"]
            },
            {
                "concept_id": "vue-router",
                "name": "Vue Router",
                "description": "Vue.js官方路由管理器",
                "category": "路由管理",
                "tags": ["Vue", "路由", "SPA"]
            },
            {
                "concept_id": "vuex",
                "name": "Vuex",
                "description": "Vue.js应用的状态管理模式",
                "category": "状态管理",
                "tags": ["Vue", "状态管理", "数据流"]
            },
            {
                "concept_id": "vue-cli",
                "name": "Vue CLI",
                "description": "Vue.js开发的标准工具",
                "category": "开发工具",
                "tags": ["Vue", "CLI", "脚手架", "构建工具"]
            },
            {
                "concept_id": "vue-component",
                "name": "Vue组件",
                "description": "Vue.js中可复用的代码块",
                "category": "组件系统",
                "tags": ["Vue", "组件", "复用", "模块化"]
            }
        ]
        
        # 创建概念节点
        for concept in vue_concepts:
            create_query = """
            MERGE (c:Concept {concept_id: $concept_id})
            SET c.name = $name,
                c.description = $description,
                c.category = $category,
                c.tags = $tags,
                c.created_at = datetime(),
                c.updated_at = datetime()
            RETURN c.concept_id, c.name
            """
            
            result = await neo4j_client.execute_query(create_query, concept)
            if result:
                print(f"✓ 创建概念: {result[0]['c.concept_id']} - {result[0]['c.name']}")
        
        # 5. 创建概念之间的关系
        print("\n5. 创建概念关系...")
        
        relationships = [
            ("vue", "vue-router", "HAS_PLUGIN", {"description": "Vue.js使用Vue Router进行路由管理"}),
            ("vue", "vuex", "HAS_PLUGIN", {"description": "Vue.js使用Vuex进行状态管理"}),
            ("vue", "vue-cli", "HAS_TOOL", {"description": "Vue CLI是Vue.js的开发工具"}),
            ("vue", "vue-component", "HAS_FEATURE", {"description": "Vue.js支持组件化开发"}),
            ("vue-router", "vue-component", "WORKS_WITH", {"description": "Vue Router与Vue组件协同工作"}),
            ("vuex", "vue-component", "MANAGES_STATE_FOR", {"description": "Vuex管理Vue组件的状态"})
        ]
        
        for from_id, to_id, rel_type, properties in relationships:
            rel_query = """
            MATCH (from:Concept {concept_id: $from_id})
            MATCH (to:Concept {concept_id: $to_id})
            MERGE (from)-[r:%s]->(to)
            SET r += $properties,
                r.created_at = datetime()
            RETURN from.concept_id, to.concept_id, type(r)
            """ % rel_type
            
            result = await neo4j_client.execute_query(
                rel_query, 
                {"from_id": from_id, "to_id": to_id, "properties": properties}
            )
            if result:
                print(f"✓ 创建关系: {result[0]['from.concept_id']} -[{result[0]['type(r)']}]-> {result[0]['to.concept_id']}")
        
        # 6. 验证数据创建
        print("\n6. 验证数据创建...")
        
        # 检查 vue 概念
        check_query = """
        MATCH (c:Concept {concept_id: 'vue'})
        RETURN c.concept_id, c.name, c.description
        """
        vue_result = await neo4j_client.execute_query(check_query)
        
        if vue_result:
            vue_data = vue_result[0]
            print(f"✓ Vue概念已创建:")
            print(f"  ID: {vue_data['c.concept_id']}")
            print(f"  名称: {vue_data['c.name']}")
            print(f"  描述: {vue_data['c.description']}")
        
        # 7. 测试查找相关概念
        print("\n7. 测试查找相关概念...")
        
        related_query = """
        MATCH (c:Concept {concept_id: 'vue'})-[r]-(related:Concept)
        RETURN related.concept_id, related.name, type(r), r.description
        LIMIT 10
        """
        related_results = await neo4j_client.execute_query(related_query)
        
        print(f"找到 {len(related_results)} 个与 vue 相关的概念:")
        for record in related_results:
            print(f"  - {record['related.concept_id']} ({record['related.name']})")
            print(f"    关系: {record['type(r)']}")
            print(f"    描述: {record['r.description']}")
            print()
        
        # 8. 关闭连接
        print("\n8. 关闭连接...")
        await context_orchestrator.shutdown()
        print("✓ 连接已关闭")
        
        print("\n=== Vue概念数据创建完成 ===")
        print("\n现在可以重新测试 MCP find_related_concepts 工具:")
        print('搜索参数: {"concept_id": "vue"}')
        print("预期结果: 应该能找到与vue相关的概念")
        
    except Exception as e:
        print(f"❌ 创建概念数据时出错: {e}")
        import traceback
        traceback.print_exc()
        
        # 确保连接关闭
        try:
            await context_orchestrator.shutdown()
        except:
            pass

if __name__ == "__main__":
    asyncio.run(create_vue_concept_data())